package com.newtouch.krd_app.view;

import static com.newtouch.krd_app.util.ConstUtil.WidgetViewWebDelayTime;
import static com.newtouch.krd_app.util.ConstUtil.WidgetViewWebPeriodTime;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;
import com.newtouch.krd_app.R;
import com.newtouch.krd_app.http.api.TerminalApi;
import com.newtouch.krd_app.util.BaseUrlUtil;
import com.newtouch.krd_app.util.ControllerInterface;
import com.newtouch.krd_app.util.DeviceUtil;
import com.newtouch.krd_app.util.SPUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * author : TQ
 * time   : 2023/2/14
 * desc   :
 */
public class WidgetViewWeb extends WidgetView {
    private AgentWeb webview;
    private int webContentHeight;
    private int scrollerHeight = 1;
    private FrameLayout fl_layout;


    private com.just.agentweb.WebViewClient mWebViewClient = new com.just.agentweb.WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
            Log.i("Info", "BaseWebActivity onPageStarted");
        }
    };
    private com.just.agentweb.WebChromeClient mWebChromeClient = new com.just.agentweb.WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }
    };

    /**
     * 构造函数
     *
     * @param context
     */
    public WidgetViewWeb(Context context) {
        super(context);
    }

    public WidgetViewWeb(Context context, ControllerInterface controllerInterface) {
        super(context, controllerInterface);
    }

    @Override
    public View initView() {
        view = View.inflate(context, R.layout.widget_web_view,null);
        fl_layout = view.findViewById(R.id.fl_layout);

        return view;

    }

    /**
     * 播放开始：逻辑通过注入H5js代码获取body高度，再由js代码进行滚动
     */
    @Override
    public void startPlay() {
        super.startPlay();

        //判空，terminatePlay时会对imageTimer置空
        if (timer == null) {
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {

                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            controllerInterface.playEnd();
                        }

                    });
                }
            };
        }
        //delay 4000不立即执行，等第一张显示4秒后执行
        //period 4000 间隔4秒执行循环
        timer.schedule(timerTask,BaseUrlUtil.getInstance().isConnect?WidgetViewWebDelayTime:1000);
    }

    @Override
    public void terminatePlay() {
        super.terminatePlay();
        if (fl_layout!=null){
            fl_layout.removeAllViews();
            fl_layout = null;
        }
    }

    @Override
    public View getView() {
        return super.getView();
    }

    @Override
    public TerminalApi.Bean.FilesDTO getFilesDTO() {
        return super.getFilesDTO();
    }

    @Override
    public void setFilesDTO(TerminalApi.Bean.FilesDTO filesDTO) {
        super.setFilesDTO(filesDTO);
//            webview.loadUrl(" https://mbd.baidu.com/newspage/data/landingshare?context=%7B%22nid%22:%22news_9341866203076394990%22%7D&pageType=1&isWiseFrom=1");
//            webview.loadUrl("http://218.6.242.123:18000/file-server?link=http://218.6.242.123:18000/group1/M00/00/19/rBDYiWP9UXWAeCfFAAdHI3-cHS054.docx&notice=以“抓现场、抓明白人、抓监督”为具体举措，“深化认识、细化措施、强化责任、优&h5=true");
        String notice = (String) SPUtils.get(context,"Notice","Notice");
        String url = BaseUrlUtil.getInstance().getCurrentUrl().get("serverVueUrl")+"?link="+filesDTO.getFilePath()+"&notice="+notice+"&H5=true";

        if (BaseUrlUtil.getInstance().isConnect){
            webview = AgentWeb.with((Activity) context)
                    .setAgentWebParent(fl_layout, new LinearLayout.LayoutParams(-1, -1))
                    .useDefaultIndicator()
                    .setWebChromeClient(mWebChromeClient)
                    .setWebViewClient(mWebViewClient)
                    .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                    .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                    .interceptUnkownUrl() //拦截找不到相关页面的Scheme
                    .createAgentWeb()
                    .ready()
                    .go(url);
        }

    }

    @SuppressLint("JavascriptInterface")
    public static class JavascriptInterface {

        WidgetViewWeb widgetViewWeb;
        /**
         * 构造方法
         */

        private final Context context;

        public JavascriptInterface(Context context,WidgetViewWeb widgetViewWeb) {
            this.context = context;
            this.widgetViewWeb = widgetViewWeb;
        }

        /**
         * 用于获取H5的内容body 高度
         */

        @android.webkit.JavascriptInterface
        public void onGetWebContentHeight(int height) {
            widgetViewWeb.webContentHeight = height;
            Log.e("TAG", "onGetWebContentHeight: "+height);
        }
    }

    @Override
    public int getDuration() {
        return (int) WidgetViewWebDelayTime;

    }
}

